package com.tobehonor.satokensample.loginsample.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tobehonor.satokensample.mybatiscommon.entity.SysUser;
import com.tobehonor.satokensample.mybatiscommon.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("/userInfo")
@RestController
public class LoginController {
    
    private ISysUserService sysUserService;
    
    public LoginController(ISysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }
    
    @GetMapping("/login")
    public SaResult login(String name, String pwd) {
        SysUser userInfo = sysUserService.getOne(
                new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, name).eq(SysUser::getStatus, "1"));
        log.info("用户信息: {}", JSONUtil.toJsonStr(userInfo));
        if (userInfo == null) {
            return SaResult.error("用户名或密码错误");
        }

        String md5Pwd = SecureUtil.md5(pwd);
        if (!StrUtil.equals(md5Pwd, userInfo.getPassword())) {
            return SaResult.error("用户名或密码错误");
        }
        StpUtil.login(userInfo.getUserId());
        return SaResult.ok();
    }
    
    @GetMapping("/isLogin")
    public SaResult isLogin() {
        return StpUtil.isLogin() ? SaResult.ok() : SaResult.error("未登录");
    }
    
    @GetMapping("/getTokenInfo")
    public SaResult getTokenInfo() {
        return SaResult.ok().set("tokenInfo", StpUtil.getTokenInfo());
    }
    
    @GetMapping("/logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }
}
